import React, { useState, memo, useEffect, useRef, useCallback } from 'react'
import { NavLink } from 'react-router-dom'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'

import { getSizeImage, formatMinuteSecond, getPlaySong } from '@/utils/format-utils'

import { Slider, message } from 'antd'
import { PlaybarWrapper, Control, PlayInfo, Operator } from './style'
import { getSongDetailAction, changeSequenceAction, changeCurrentIndexAndSong, changeCurrentLyricIndexAction } from '../store/actionCreators'
import { formatDate } from '../../../utils/format-utils'



export default memo(function HYAppPlayerBar () {
  // props and state
  const [currentTime, setCurrentTime] = useState(0);
  const [progress, setProgress] = useState(0);
  const [isChanging, setIsChanging] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);

  // redux hook
  const {
    currentSong,
    sequence,
    playList,
    lyricList,
    currentLyricIndex
  } = useSelector(state => ({
    currentSong: state.getIn(['player', 'currentSong']),
    sequence: state.getIn(['player', 'sequence']),
    playList: state.getIn(['player', 'playList']),
    lyricList: state.getIn(['player', 'lyricList']),
    currentLyricIndex: state.getIn(['player', 'currentLyricIndex'])
  }), shallowEqual)
  const dispatch = useDispatch();

  // other hook
  const audioRef = useRef();
  useEffect(() => {
    dispatch(getSongDetailAction(167876))
  }, [dispatch])

  useEffect(() => {
    audioRef.current.src = getPlaySong(currentSong.id);
    audioRef.current.play().then(res => {
      setIsPlaying(true);
    }).catch(err => {
      setIsPlaying(false);
    })
  }, [currentSong])

  const picUrl = (currentSong.al && currentSong.al.picUrl) || "";
  const singlerName = (currentSong.ar && currentSong.ar[0].name) || '未知歌手'
  const duration = (currentSong.dt) || 0
  const showCurrentTime = formatDate(currentTime, 'mm:ss');

  const playMusic = useCallback(
    () => {
      isPlaying ? audioRef.current.pause() : audioRef.current.play();
      setIsPlaying(!isPlaying);
    }, [isPlaying])

  const changeMusic = (tag) => {
    dispatch(changeCurrentIndexAndSong(tag));
  }

  const timeUpdate = (e) => {
    const currentTime = e.target.currentTime;
    if (!isChanging) {
      setCurrentTime(e.target.currentTime * 1000)
      setProgress(currentTime * 1000 / duration * 100);
    }

    // 获取当前的歌词
    let i = 0;
    for (; i < lyricList.length; i++) {
      let lyricItem = lyricList[i];
      if (currentTime * 1000 < lyricItem.time) {
        break;
      }
    }
    if (currentLyricIndex !== i - 1) {
      dispatch(changeCurrentLyricIndexAction(i - 1));
      console.log(lyricList[i - 1]);
      const content = lyricList[i - 1] && lyricList[i - 1].content;
      message.open({
        content: content,
        duration: 0,
        key: "lyric",
        className: 'lyric-class'
      })
    }
  }


  const handleMusicEnded = (e) => {
    if (sequence === 2) { //单曲循环
      audioRef.current.currentTime = 0;
      audioRef.current.play();
    } else {
      dispatch(changeCurrentIndexAndSong(1))
    }
  }

  const changeSequence = () => {
    let currentSequence = sequence + 1;
    if (currentSequence > 2) {
      currentSequence = 0;
    }
    dispatch(changeSequenceAction(currentSequence));
  }

  const sliderChange = useCallback(
    (value) => {
      setIsChanging(true);
      const currentTime = value / 100 * duration;
      setCurrentTime(currentTime);
      setProgress(value);
    }, [duration])

  const sliderAfterChange = useCallback(
    (value) => {
      const currentTime = value / 100 * duration / 1000;
      audioRef.current.currentTime = currentTime;
      setCurrentTime(currentTime * 1000);
      setIsChanging(false);

      if (!isPlaying) {
        playMusic();
      }
    }, [duration, isPlaying, playMusic])

  return (
    <PlaybarWrapper className="sprite_playbar">
      <div className="content wrap-v2">
        <Control isPlaying={isPlaying}>
          <button className="sprite_playbar prev"
            onClick={e => changeMusic(-1)}></button>
          <button className="sprite_playbar play"
            onClick={e => playMusic()}></button>
          <button className="sprite_playbar next"
            onClick={e => changeMusic(1)}></button>
        </Control>
        <PlayInfo>
          <div className="image">
            <NavLink to="/discover/player">
              <img src={getSizeImage(picUrl, 35)} alt="" />
            </NavLink>
          </div>
          <div className="info">
            <div className="song">
              <span className="song-name">{currentSong.name}</span>
              <a className="singer-name" href="/todo">{singlerName}</a>
            </div>
            <div className="progress">
              <Slider
                value={progress}
                onChange={sliderChange}
                onAfterChange={sliderAfterChange} />
              <div className="time">
                <span className="now-time">{showCurrentTime}</span>
                <span className="divider">/</span>
                <span className="duration">{formatMinuteSecond(duration)}</span>
              </div>
            </div>
          </div>
        </PlayInfo>
        <Operator sequence={sequence}>
          <div className="left">
            <button className="sprite_playbar btn favor"></button>
            <button className="sprite_playbar btn share"></button>
          </div>
          <div className="right sprite_playbar">
            <button className="sprite_playbar btn volume"></button>
            <button className="sprite_playbar btn loop" onClick={e => changeSequence()}></button>
            <button className="sprite_playbar btn playlist">{playList.length}</button>
          </div>
        </Operator>
      </div>
      <audio
        ref={audioRef}
        onTimeUpdate={e => timeUpdate(e)}
        onEnded={e => handleMusicEnded(e)}
      />
    </PlaybarWrapper>
  )
})
